package com.thread.Demo02;



import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建方式3: 实现Callable接口
/*
* 可以定义返回值
* 可以抛出异常
* */
public class TestCallable implements Callable<Boolean> {
    private String url;
    private String name;//保存的文件名
    //重写call方法
    @Override
    public Boolean call() throws Exception {
        ImgDownloader imgDownloader = new ImgDownloader();
        imgDownloader.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
        return true;
    }

    //构造方法
    public TestCallable(String url,String name){
        this.url = url;
        this.name = name;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://store.hituyu.com/LqiGjDyCFyeQfqRyPYcnMaqJpIMtxsFK..png", "1.jpg");
        TestCallable t2 = new TestCallable("https://store.hituyu.com/CqKCCwCkJhtBCnUoEUeBuGvUsqPWkZMC..png", "2.jpg");
        TestCallable t3 = new TestCallable("https://store.hituyu.com/GgCPAtESyYKBXTgYxjBvuimKDUlqEcte..png", "3.jpg");

        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);

        //获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();

        //关闭服务
        ser.shutdown();

    }
}

class ImgDownloader{
    //下载方法
    public void downloader(String url,String name){
        //使用文件工具类
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader wrong");
        }
    }
}
    